package com.lhkj.ct.base.utils.file.word;


import com.alibaba.fastjson2.JSON;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.lhkj.ct.base.exception.SystemException;
import com.lhkj.ct.base.utils.ServletUtils;
import com.lhkj.ct.base.utils.file.FileUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.ooxml.POIXMLDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 */
public class PoiWordUtils {

    private static final Logger logger = LoggerFactory.getLogger(PoiWordUtils.class);

    public static InputStream document2Os(POIXMLDocument document) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//二进制OutputStream
        document.write(baos);//文档写入流
        return new ByteArrayInputStream(baos.toByteArray());
    }

    /**
     * word转换为pdf下载
     */
    public static void wordDownload(POIXMLDocument document, String fileName){
        HttpServletResponse response = ServletUtils.getResponse();
        try {
            FileUtils.setAttachmentResponseHeader(response, fileName);
            document.write(response.getOutputStream());
        } catch (IOException e) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(200);
            try {
                response.getWriter().write(JSON.toJSONString(ExceptionUtils.getRootCauseMessage(e)));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * word转换为pdf下载
     */
    public static void wordToPdfDownload(POIXMLDocument document, String pdfName){
        HttpServletResponse response = ServletUtils.getResponse();
        // 获取凭证，去除水印
        if (!AsposeWordsUtil.getLicense()) {
            throw new SystemException("PDF生成授权凭证无效");
        }
        try {
            FileUtils.setAttachmentResponseHeader(response, pdfName);
            //通过aspose-words.jar中的类转换文件
            Document doc = new Document(PoiWordUtils.document2Os(document));
            doc.save(response.getOutputStream(), SaveFormat.PDF);
        } catch (Exception e) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(200);
            logger.error("导出文件异常，{}", e.getMessage());
            try {
                response.getWriter().write(JSON.toJSONString(ExceptionUtils.getRootCauseMessage(e)));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * word转换为pdf下载
     */
    public static void download(Document document, String fileName, int saveFormat){
        HttpServletResponse response = ServletUtils.getResponse();
        // 获取凭证，去除水印
        if (!AsposeWordsUtil.getLicense()) {
            throw new SystemException("PDF生成授权凭证无效");
        }
        try {
            FileUtils.setAttachmentResponseHeader(response, fileName);
            document.save(response.getOutputStream(), saveFormat);
        } catch (Exception e) {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "application/json;charset=UTF-8");
            response.setStatus(200);
            logger.error("导出文件异常，{}", e.getMessage());
            try {
                response.getWriter().write(JSON.toJSONString(ExceptionUtils.getRootCauseMessage(e)));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
